package com.spider.im.chat.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.im.chat.entity.ChatGroupUser;
import com.spider.im.chat.mapper.ChatGroupUserMapper;
import com.spider.im.chat.req.ChatGroupUserReq;
import com.spider.im.chat.service.ChatGroupUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 聊天组和组员的关系表 服务实现类
 * </p>
 *
 * @author joy
 * @since 2025-04-23
 */
@Service
public class ChatGroupUserServiceImpl extends ServiceImpl<ChatGroupUserMapper, ChatGroupUser> implements ChatGroupUserService {

    @Override
    public List<Long> saveGroupUser(ChatGroupUserReq chatGroupUserReq) {
        List<Long> userIds = new ArrayList<>(chatGroupUserReq.getUserIds());

        //根据用户ID 和群ID查询新加入的人员中已经存在的用户id集合
        List<Long> existUserIds = this.list(new LambdaQueryWrapper<ChatGroupUser>().eq(ChatGroupUser::getGroupId, chatGroupUserReq.getGroupId()).in(ChatGroupUser::getUserId, userIds))
                .stream().map(ChatGroupUser::getUserId).toList();
        if (CollectionUtil.isNotEmpty(existUserIds)) {
            //移除参数集合中的已经存在的用户
            userIds.removeAll(existUserIds);
        }
        //批量插入不存在的用户
        if (CollectionUtil.isNotEmpty(userIds)) {
            userIds.forEach(userId -> {
                 this.save(ChatGroupUser.builder().groupId(chatGroupUserReq.getGroupId()).userId(userId).build());
            });
        }

        return userIds;
    }
}
